var xiaoxin = {
    server: false,
    status: true,
    once: true,
    onceFun: function () {
        if (!this.once) {
            return;
        }
        this.once = false;
        suspensionBall('ballId')
        createTerminal()
    },
    run: function () {

    },
    filterReq: function (url, responseData) { },
    commands: {
        'help': '可用命令：help, clear',
        'clear': () => { output.innerHTML = ''; },
    },
    init: function () {
        this.onceFun()
    }
};

function suspensionBall(dragId) {
    var startEvt, moveEvt, endEvt
    // 判断是否支持触摸事件
    if ('ontouchstart' in window) {
        startEvt = 'touchstart'
        moveEvt = 'touchmove'
        endEvt = 'touchend'
    } else {
        startEvt = 'mousedown'
        moveEvt = 'mousemove'
        endEvt = 'mouseup'
    }
    // 获取元素
    var drag = document.getElementById(dragId)
    drag.style.position = 'absolute'
    drag.style.cursor = 'pointer'
    // 标记是拖曳还是点击
    var isClick = true
    var disX, disY, left, top, starX, starY

    drag.addEventListener(startEvt, function (e) {
        // 阻止页面的滚动，缩放
        e.preventDefault()
        // 兼容IE浏览器
        var e = e || window.event
        isClick = true
        // 手指按下时的坐标
        starX = e.touches ? e.touches[0].clientX : e.clientX
        starY = e.touches ? e.touches[0].clientY : e.clientY
        // 手指相对于拖动元素左上角的位置
        disX = starX - drag.offsetLeft
        disY = starY - drag.offsetTop
        // 按下之后才监听后续事件 
        drag.addEventListener(endEvt, endFun)
    })

    function endFun(e) {
        if (isClick) { // 点击
            createTerminal()
            if (typeof xiaoxin == "object") {
                xiaoxin.run()
            } else {
                console.info("小信插件初始化失败")
            }
        }
    }
}

var output = false

function createTerminal(dispaly) {
    if (document.getElementById('terminal-container')) {
        document.getElementById('terminal-container').style.visibility = "visible";
        return;
    }
    // 创建终端容器
    const terminalContainer = document.createElement('div');
    terminalContainer.id = 'terminal-container';
    terminalContainer.style.visibility = "hidden"
    terminalContainer.innerHTML = `
        <div id="terminal-header"> 
            <button id="close-btn">X</button>
        </div>
        <div id="terminal">
            <div id="output"></div>
            <div id="input-line">
                <span id="prompt">$</span>
                <input type="text" id="command-input" autofocus="autofocus">
            </div>
        </div> 
    `;

    // 添加终端样式
    const style = document.createElement('style');
    style.innerHTML = `
        #terminal-container { 
            width: 1000px;
            height: 800px;
            background-color: #1e1e1e;
            color: #00ff00;
            border-radius: 8px;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
            display: flex;
            flex-direction: column;
            z-index: 9999; 
        }

        #terminal-header {
            display: flex;
            justify-content: flex-end;
            background-color: #333;
            padding: 5px;
            border-top-left-radius: 8px;
            border-top-right-radius: 8px;
            cursor: move;
        }

        #terminal-header button {
            background-color: #444;
            color: #fff;
            border: none;
            padding: 5px 10px;
            margin-left: 5px;
            border-radius: 3px;
            cursor: pointer;
        }

        #terminal-header button:hover {
            background-color: #666;
        }

        #terminal {
            flex-grow: 1;
            display: flex;
            flex-direction: column;
            padding: 0px;
        }

        #output {
            height:730px;
            flex-grow: 1;
            overflow-y: auto;
            margin-bottom: 10px; 
            white-space: pre-wrap; /* 保留换行符 */
        }

        #input-line {
            display: flex;
            align-items: center;
        }

        #prompt {
            margin-right: 10px;
        }

        #command-input {
            flex-grow: 1;
            background: none;
            border: none;
            color: #00ff00;
            outline: none;
            font-family: inherit;
            font-size: 16px;
        }

        .hidden {
            display: none;
        }
    `;
    document.body.appendChild(style);

    // 添加终端到页面
    document.body.appendChild(terminalContainer);

    // 处理终端逻辑
    const commandInput = document.getElementById('command-input');
    output = document.getElementById('output');
    const closeBtn = document.getElementById('close-btn');
    var commands = xiaoxin.commands;
    // 处理输入命令
    function handleCommand(command) {
        const parts = command.trim().split(/\s+/);
        const funcName = parts[0]; // 第一个为函数名
        const arg = parts.slice(1).join(" "); // 剩余部分拼接为空格分隔的参数字符串 
        commands = xiaoxin.commands;
        if (commands[funcName]) {
            if (typeof commands[funcName] === 'function') {
                commands[funcName](arg);
            } else {
                appendOutput(commands[command]);
            }
        } else {
            appendOutput(`Command not found: ${command}`);
        }
    }

    // 监听输入框的 Enter 键
    commandInput.addEventListener('keydown', (event) => {
        if (event.key === 'Enter') {
            const command = commandInput.value.trim();
            appendOutput(command);
            handleCommand(command);
            commandInput.value = '';
        }
    });

    // 关闭按钮功能
    closeBtn.addEventListener('click', () => {
        terminalContainer.style.visibility = "hidden";
    });

    // 拖拽功能
    let isDragging = false;
    let startX, startY, initialLeft, initialTop;

    const header = document.getElementById('terminal-header');

    header.addEventListener('mousedown', (e) => {
        isDragging = true;
        startX = e.clientX;
        startY = e.clientY;
        const rect = terminalContainer.getBoundingClientRect();
        initialLeft = rect.left;
        initialTop = rect.top;

        document.addEventListener('mousemove', onMouseMove);
        document.addEventListener('mouseup', onMouseUp);
    });

    function onMouseMove(e) {
        if (isDragging) {
            const deltaX = e.clientX - startX;
            const deltaY = e.clientY - startY;
            terminalContainer.style.left = `${initialLeft + deltaX}px`;
            terminalContainer.style.top = `${initialTop + deltaY}px`;
            terminalContainer.style.transform = 'none';  // 清除translate影响
        }
    }

    function onMouseUp() {
        isDragging = false;
        document.removeEventListener('mousemove', onMouseMove);
        document.removeEventListener('mouseup', onMouseUp);
    }

}

// 将命令结果输出到终端
function appendOutput(text) {
    if (output) {
        const outputLine = document.createElement('div');
        outputLine.textContent = `$ ${text}`;
        output.appendChild(outputLine);
        output.scrollTop = output.scrollHeight;
    }
}

// 解码base64
function base64ToArrayBuffer(base64) {
    const binaryString = atob(base64);
    const len = binaryString.length;
    const bytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
        bytes[i] = binaryString.charCodeAt(i);
    }
    return bytes.buffer;
}

// 解压缩
function decompress(arrayBuffer) {
    const uint8Array = new Uint8Array(arrayBuffer);
    const decompressedData = pako.inflate(uint8Array);
    return decompressedData;
}

// 日志输出
var lastLog = "";
function addLog(text) {
    let date = new Date().toLocaleString()
    let t = `[LOG]  ${date} - ${text}`;
    if (text == lastLog) {
        return;
    }
    lastLog = text;
    appendOutput(t)
}

xiaoxin.init();

// (function (xhr) {
//     var XHR = XMLHttpRequest.prototype;
//     var open = XHR.open;
//     var send = XHR.send;
//     var setRequestHeader = XHR.setRequestHeader;
//     XHR.bot = true;
//     XHR.open = function (method, url) {
//         this._method = method;
//         this._url = url;
//         this._requestHeaders = {};
//         this._startTime = (new Date()).toISOString();
//         return open.apply(this, arguments);
//     };

//     XHR.setRequestHeader = function (header, value) {
//         this._requestHeaders[header] = value;
//         return setRequestHeader.apply(this, arguments);
//     };
//     XHR.send = function (postData) {
//         this.addEventListener('load', function () {
//             var endTime = (new Date()).toISOString();
//             var myUrl = this._url ? this._url.toLowerCase() : this._url;
//             if (myUrl) {
//                 if (postData) {
//                     if (typeof postData === 'string') {
//                         try {
//                             this._requestHeaders = postData;
//                         } catch (err) {
//                             console.log('Request Header JSON decode failed, transfer_encoding field could be base64');
//                             console.log(err);
//                         }
//                     } else if (typeof postData === 'object' || typeof postData === 'array' || typeof postData === 'number' || typeof postData === 'boolean') {
//                         // do something if you need
//                     }
//                 }
//                 var responseHeaders = this.getAllResponseHeaders();
//                 if (this.responseType != 'blob' && this.responseText) {
//                     try {
//                         if (typeof xiaoxin == "object") {
//                             xiaoxin.filterReq(myUrl, this.responseText)
//                         }
//                     } catch (err) {
//                         console.log("Error in responseType try catch");
//                         console.log(err);
//                     }
//                 }
//             }
//         });
//         return send.apply(this, arguments);
//     };

// })(XMLHttpRequest);


// 劫持 fetch
const originalFetch = window.fetch;
window.fetch = async (...args) => {
    try {
        const response = await originalFetch(...args);
        // 克隆副本用于读取数据
        const clone = response.clone();
        // 根据需要选择 .json() / .text() / .blob() 
        clone.text().then(data => {
            if (args[1] && args[1].body && args[1].headers) {
                if (args[1].headers["Content-Type"] && args[1].headers["Content-Type"].indexOf("application/json") > -1) {
                    xiaoxin.filterReq(args[0], JSON.parse(args[1].body), data)
                }
            } else {
                xiaoxin.filterReq(args[0], false, data)
            }
            // if (args[0] == "") {
            //     if (args[1] && args[1].headers && args[1].headers["Next-Action"]) {
            //         console.log('Fetch called with:', args, data);
            //     }
            // }
        });
        return response;
    } catch (e) {
        console.error('fetch interception error:', e);
        throw e;
    }
};

